<template>
  <el-button :loading="loading" @click="handleExport" type="warning" plain icon="Upload">
    {{ buttonText }}
    <!-- {{ t("button.export") }} -->
  </el-button>
</template>

<script setup>
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { ref } from "vue";
import { ElMessage } from "element-plus";
import { exportDataToExcel } from "@/utils/file/exportHelper";

// Define component props
const props = defineProps({
  columns: {
    type: Array,
    required: true,
  },
  data: {
    type: Array,
    required: true,
  },
  filename: {
    type: String,
    default: "",
  },
});

// Create refs to control the loading state and button text
const loading = ref(false);
const buttonText = ref(t("button.export"));
const handleExport = async () => {
  loading.value = true;
  buttonText.value = t("message.exporting"); // "正在导出中...";

  // 确保 DOM 更新完成后再执行导出逻辑
  await nextTick();
  // 添加一个小的延迟，确保状态已经更新
  await new Promise((resolve) => setTimeout(resolve, 2000));
  try {
    const message = await exportDataToExcel({
      filename: props.filename,
      columns: props.columns,
      data: props.data,
    });
    console.log("导出成功:", `${t("message.exportSuccess")}: ${message}`);
    ElMessage.success(`${t("message.exportSuccess")}: ${message}`);
  } catch (error) {
    ElMessage.error(
      `${t("message.exportFailed")}: ${error.message || t("message.unknownError")}`
    );
  } finally {
    buttonText.value = t("button.export");
    loading.value = false;
  }
};
</script>
